package cytj.setup.fragment;

import android.app.Fragment;
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import cytj.setup.R;
import cytj.setup.activity.SetupActivity;
import cytj.setup.base.MyAPP;
import cytj.setup.util.CharacterTool;


public class NodesSetupFragment extends Fragment implements View.OnClickListener {
    /**
     * NodesSetupFragment的视图
     */
    private View view;
    /**
     * 基站ID、显示基站ID、节点ID、节点休眠时长的编辑框
     */
    private EditText editText_baseID, editText_showBaseID, editText_nodesID, editText_nodesSleepTime;
    /**
     * 节点开始休眠时间的文本框
     */
    private TextView textView_nodesSleepStartTimeSelector;
    /**
     * 节点休眠数量、节点休眠方式、节点停车状态的下拉框
     */
    private Spinner spinner_nodesNum, spinner_nodesSleepWay, spinner_nodesStatus;
    /**
     * 调试用TAG
     */
    private static final String TAG = "LTP";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_nodes_setup, container, false);
        initView();
        return view;
    }

    /**
     * 控件初始化
     */
    private void initView() {
        editText_baseID = (EditText) view.findViewById(R.id.editText_baseID_nodesSetupFragment);
        editText_showBaseID = (EditText) view.findViewById(R.id.editText_showBaseID_nodesSetupFragment);
        editText_nodesID = (EditText) view.findViewById(R.id.editText_nodesID_nodesSetupFragment);
        editText_nodesSleepTime = (EditText) view.findViewById(R.id.editText_nodesSleepTime_nodesSetupFragment);
        spinner_nodesNum = (Spinner) view.findViewById(R.id.spinner_nodesNum_nodesSetupFragment);
        spinner_nodesSleepWay = (Spinner) view.findViewById(R.id.spinner_nodesSleepWay_nodesSetupFragment);
        spinner_nodesStatus = (Spinner) view.findViewById(R.id.spinner_nodesStatus_nodesSetupFragment);
        // 设置节点休眠、节点重启、更改节点状态的按键
        Button button_setNodesSleep = (Button) view.findViewById(R.id.button_setNodesSleep_nodesSetupFragment);
        button_setNodesSleep.setOnClickListener(this);
        Button button_restartNodes = (Button) view.findViewById(R.id.button_restartNodes_nodesSetupFragment);
        button_restartNodes.setOnClickListener(this);
        Button button_changeNodesStatus = (Button) view.findViewById(R.id.button_changeNodesStatus_nodesSetupFragment);
        button_changeNodesStatus.setOnClickListener(this);
        textView_nodesSleepStartTimeSelector = (TextView) view.findViewById(R.id.textView_nodesSleepStartTimeSelector_nodesSetupFragment);
        textView_nodesSleepStartTimeSelector.setOnClickListener(this);
        view.findViewById(R.id.relativeLayout_nodesSetupFragment).setOnClickListener(this);
    }

    /**
     * 根据节点休眠数量获取节点休眠数量类型码
     *
     * @param nodesNum 最高1位表示全部节点或者单个节点:1-基站下全部节点（8），0-单个节点
     */

    private String getNodesNum(String nodesNum) {
        String nodesNumCode = "0";
        switch (nodesNum) {
            case "基站下全部节点":
                nodesNumCode = "8";
                break;
            case "单个节点":
                nodesNumCode = "0";
                break;
        }
        return nodesNumCode;
    }

    /**
     * 根据节点停车状态获取节点停车状态类型码
     *
     * @param nodesStatus 0x01-将节点车位状态更改为有车，0x02-将节点车位状态更改为无车
     */

    private String getNodesStatus(String nodesStatus) {
        String nodesStatusCode = "0";
        switch (nodesStatus) {
            case "有车":
                nodesStatusCode = "01";
                break;
            case "无车":
                nodesStatusCode = "02";
                break;
        }
        return nodesStatusCode;
    }

    /**
     * 根据节点休眠方式获取节点休眠方式类型码
     *
     * @param nodesSleepWay 0x0-停止休眠，0x1-每天，0x2-当天
     */

    private String getNodesSleepWay(String nodesSleepWay) {
        String nodesSleepWayCode = "0";
        switch (nodesSleepWay) {
            case "停止休眠":
                nodesSleepWayCode = "0";
                break;
            case "每天":
                nodesSleepWayCode = "1";
                break;
            case "当天":
                nodesSleepWayCode = "2";
                break;
        }
        return nodesSleepWayCode;
    }

    public void setShowBaseID(String baseID) {
        editText_showBaseID.setText(baseID);
    }

    @Override
    public void onClick(View v) {
        String baseId = editText_baseID.getText().toString();
        String nodesId = editText_nodesID.getText().toString();
        editText_showBaseID.setText("");
        switch (v.getId()) {
            case R.id.textView_nodesSleepStartTimeSelector_nodesSetupFragment:
                // 点击选择节点开始休眠时间文本后弹出时间选择器进行选择
                int hour = 0;
                int min = 0;
                // 获取节点开始休眠时间文本的文本内容作为事件选择器的默认时间
                if (!textView_nodesSleepStartTimeSelector.getText().toString().isEmpty()) {
                    String time = textView_nodesSleepStartTimeSelector.getText().toString();
                    hour = Integer.parseInt(time.substring(0, 2));
                    min = Integer.parseInt(time.substring(3, 5));
                }
                TimePickerDialog time = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {

                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        String hour = Integer.toString(hourOfDay);
                        String min = Integer.toString(minute);
                        if (hourOfDay < 10) {
                            hour = "0" + hour;
                        }
                        if (minute < 10) {
                            min = "0" + min;
                        }
                        textView_nodesSleepStartTimeSelector.setText(hour + ":" + min);
                    }
                }, hour, min, true);
                time.show();
                break;
            case R.id.relativeLayout_nodesSetupFragment:
                // 点击EditText外部隐藏键盘
                InputMethodManager imm = (InputMethodManager)
                        getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                break;
            case R.id.button_setNodesSleep_nodesSetupFragment:
                // 点击设置节点休眠的按键
                String nodesSleepWay = getNodesNum(spinner_nodesNum.getSelectedItem().toString()) + getNodesSleepWay(spinner_nodesSleepWay.getSelectedItem().toString());
                String nodesSleepTime = editText_nodesSleepTime.getText().toString();
                if (!MyAPP.getMyAPPInstance().isBluetoothConnected()) {
                    Toast.makeText(getActivity(), "请先连接蓝牙！", Toast.LENGTH_SHORT).show();
                } else if (baseId.length() != 6 || nodesId.length() != 6) {
                    Toast.makeText(getActivity(), "基站Id或节点Id有误！", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(textView_nodesSleepStartTimeSelector.getText().toString()) && TextUtils.isEmpty(nodesSleepTime)) {
                    Toast.makeText(getActivity(), "请将信息填写完整", Toast.LENGTH_SHORT).show();
                } else {
                    String nodesSleepStartTimeHours = textView_nodesSleepStartTimeSelector.getText().toString().substring(0, 2);
                    String nodesSleepStartTimeMinutes = textView_nodesSleepStartTimeSelector.getText().toString().substring(3, 5);
                    nodesSleepStartTimeHours = CharacterTool.intToHexString(nodesSleepStartTimeHours, 1);
                    nodesSleepStartTimeMinutes = CharacterTool.intToHexString(nodesSleepStartTimeMinutes, 1);
                    nodesSleepTime = CharacterTool.intToHexString(nodesSleepTime, 2);
                    String protocol1 = "ABAB" + baseId + "800900" + nodesSleepWay + nodesId + nodesSleepStartTimeHours + nodesSleepStartTimeMinutes + nodesSleepTime;
                    String xor1 = CharacterTool.xor(CharacterTool.hexStringToBytes(protocol1), protocol1.length() / 2);
                    protocol1 = protocol1.substring(0, 14) + xor1 + protocol1.substring(14);
                    Log.d(TAG, "发送设置节点休眠的协议：" + CharacterTool.splitData(protocol1));
                    ((SetupActivity) getActivity()).bluetoothService.write(CharacterTool.hexStringToBytes(protocol1));
                    ((SetupActivity) getActivity()).showProgressDialog("操作中，请稍候... ");
                    nodesSetupCountDownTimer.start();
                }
                break;
            case R.id.button_changeNodesStatus_nodesSetupFragment:
                // 点击纠正节点状态的按键
                String nodesStatus = getNodesStatus(spinner_nodesStatus.getSelectedItem().toString());
                if (!MyAPP.getMyAPPInstance().isBluetoothConnected()) {
                    Toast.makeText(getActivity(), "请先连接蓝牙！", Toast.LENGTH_SHORT).show();
                } else if (baseId.length() != 6 || nodesId.length() != 6) {
                    Toast.makeText(getActivity(), "基站Id或节点Id有误！", Toast.LENGTH_SHORT).show();
                } else {
                    String protocol2 = "ABAB" + baseId + "820500" + nodesStatus + nodesId;
                    String xor2 = CharacterTool.xor(CharacterTool.hexStringToBytes(protocol2), protocol2.length() / 2);
                    protocol2 = protocol2.substring(0, 14) + xor2 + protocol2.substring(14);
                    Log.d(TAG, "发送纠正节点状态的协议：" + CharacterTool.splitData(protocol2));
                    ((SetupActivity) getActivity()).bluetoothService.write(CharacterTool.hexStringToBytes(protocol2));
                    ((SetupActivity) getActivity()).showProgressDialog("操作中，请稍候... ");
                    nodesSetupCountDownTimer.start();
                }
                break;
            case R.id.button_restartNodes_nodesSetupFragment:
                // 点击重启节点的按键
                if (!MyAPP.getMyAPPInstance().isBluetoothConnected()) {
                    Toast.makeText(getActivity(), "请先连接蓝牙！", Toast.LENGTH_SHORT).show();
                } else if (baseId.length() != 6 || nodesId.length() != 6) {
                    Toast.makeText(getActivity(), "基站Id或节点Id有误！", Toast.LENGTH_SHORT).show();
                } else {
                    String protocol3 = "ABAB" + baseId + "81050001" + nodesId;
                    String xor3 = CharacterTool.xor(CharacterTool.hexStringToBytes(protocol3), protocol3.length() / 2);
                    protocol3 = protocol3.substring(0, 14) + xor3 + protocol3.substring(14);
                    Log.d(TAG, "发送重启节点的协议：" + CharacterTool.splitData(protocol3));
                    ((SetupActivity) getActivity()).bluetoothService.write(CharacterTool.hexStringToBytes(protocol3));
                    ((SetupActivity) getActivity()).showProgressDialog("操作中，请稍候... ");
                    nodesSetupCountDownTimer.start();
                    break;
                }
        }

    }

    /**
     * 读取/写入按键按下后倒计时10秒
     */
    public CountDownTimer nodesSetupCountDownTimer = new CountDownTimer(11000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            ((SetupActivity) getActivity()).progressDialog.setMessage("操作中，请稍候... " + millisUntilFinished / 1000);
        }

        @Override
        public void onFinish() {
            Toast.makeText(getActivity(), "超时,操作失败", Toast.LENGTH_SHORT).show();
            if (((SetupActivity) getActivity()).progressDialog != null) {
                ((SetupActivity) getActivity()).progressDialog.dismiss();
            }
        }
    };
}
